import config from "./config.js";
import express from "express";
import { promisify } from "util";
import fs from "fs";

const fsReadSync = promisify(fs.readFile);
const fsWriteSync = promisify(fs.writeFile);
const app = express();
// 使用json接受数据
app.use(express.json());

app.get("/api/user/list", async (req, res) => {
  const data = await fsReadSync("./mockdb/db.json");
  console.log(data);
  if (!data) {
    res.status(404).send("Not Found");
  } else {
    const resData = JSON.parse(data);
    res.send({
      code: 200,
      data: resData.users,
    });
  }
});

app.post("/api/user/add", async (req, res) => {
  const body = req.body;
  if (!body) {
    res.status(400).send("Bad Request");
  }
  try {
    // 对数据文件进行读取操作
    const dbData = await fsReadSync("./mockdb/db.json", "utf8");
    const dbDataJSON = JSON.parse(dbData);
    const id = dbDataJSON.users.length + 1;
    body.id = id;
    dbDataJSON.users.push(body);
    // 对数据文件进行写入操作
    const err = fsWriteSync("./mockdb/db.json", JSON.stringify(dbDataJSON));
    if (!err) {
      res.status(200).send({
        message: "添加成功",
      });
    }
  } catch (error) {
    res.status(500).json(error);
  }
});

app.listen(config.port, config.hostname, () => {
  console.log(`Server running at http://${config.hostname}:${config.port}/`);
});

